package adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.text.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.MyApplication;
import data.SharedPreferencesUtils;
import entity.Voucher;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.LogUtil;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;
import view.diaLogView.CrowdRetunDialog;

/**
 * Created by liuxiaobin on 2017/5/10
 *
 */

public class VoucherAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener{
    private Context mContext;
    private int mType,mPosition;  //0代表已加载 2代表未加载
    private LayoutInflater mLayoutInflater;
    private DisplayImageOptions mDisplayImageOptions;
    List<Voucher.CanGetBean> mListCanGet;
    List<Voucher.CannotGetBean> mListCannotGet;

    /**
     * 上拉加载更多
     */
    public final int PULLUP_LOAD_MORE=0;
    /**
     * 正在加载中
     */
    public final int LOADING_MORE=1;

    /**
     * 沒有数据了
     */
    public final int LOADING_THREE=3;
    /**
     * 上拉加载更多状态-默认为0
     */
    private int load_more_status=0;



    public VoucherAdapter(Context context,List<Voucher.CanGetBean> listCanGet,List<Voucher.CannotGetBean> listCannotGet,int type){
        this.mContext = context;
        this.mListCanGet = listCanGet;
        this.mListCannotGet = listCannotGet;
        this.mType = type;
        mLayoutInflater = LayoutInflater.from(mContext.getApplicationContext());
        mDisplayImageOptions = HomeUtil.getHemeUtilNew().getDisplayImageOptions(true, R.mipmap.homepage_icon);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        if(mListCannotGet !=null  && mListCannotGet.size() <6){
            view = mLayoutInflater.inflate(R.layout.adapter_voucher, parent, false);
            VoucherHolder holder = new VoucherAdapter.VoucherHolder(mContext,view,mType);
            view.setOnClickListener(this);
            return holder;
        }else {
            if(viewType == 0 || viewType ==2){
                view = mLayoutInflater.inflate(R.layout.adapter_voucher, parent, false);
                VoucherHolder holder = new VoucherAdapter.VoucherHolder(mContext,view,mType);
                view.setOnClickListener(this);
                return holder;
            }else if(viewType == 1){
                view = mLayoutInflater.inflate(R.layout.adapter_periphery_button,parent,false);
                FootViewHolder footViewHolder=new FootViewHolder(view);
                return footViewHolder;
            }
        }
        return null;

    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if(holder instanceof VoucherHolder){
            if(mType == 0){
                int dd = position;
                TextView d = ((VoucherHolder)holder).mTVName;
                mListCannotGet.get(position).getTicketName();
                ((VoucherHolder)holder).mTVName.setText(mListCannotGet.get(position).getTicketName());
                ((VoucherHolder)holder).mTVTime.setText(mListCannotGet.get(position).getGiveTime()+"h");
                ((VoucherHolder)holder).mTVHairtime.setText(mListCannotGet.get(position).getAllotTime());
                ((VoucherHolder)holder).mTVcollartime.setText(mListCannotGet.get(position).getGetTime());
                holder.itemView.setTag(position);
                mPosition = position;
            }else if(mType == 2) {
                ((VoucherHolder)holder).mTVName.setText(mListCanGet.get(position).getTicketName());
                ((VoucherHolder)holder).mTVTime.setText(mListCanGet.get(position).getGiveTime()+"h");
                ((VoucherHolder)holder).mTVHairtime.setText(mListCanGet.get(position).getAllotTime());
                holder.itemView.setTag(position);
                mPosition = position;
            }
        }else if(holder instanceof FootViewHolder){
            FootViewHolder footViewHolder=(FootViewHolder)holder;
            switch (load_more_status){
                case PULLUP_LOAD_MORE:
                    footViewHolder.tv_Name.setText("上拉加载更多...");
                    footViewHolder.mProgressBar.setVisibility(View.VISIBLE);
                    break;
                case LOADING_MORE:
                    footViewHolder.tv_Name.setText("正在加载更多数据...");
                    footViewHolder.mProgressBar.setVisibility(View.VISIBLE);
                    break;
                case LOADING_THREE:
                    footViewHolder.tv_Name.setText("数据加载完成");
                    footViewHolder.mProgressBar.setVisibility(View.GONE);
                    break;
            }
        }

    }

    /**
     * 进行判断是普通Item视图还是FootView视图
     */
    @Override
    public int getItemViewType(int position) {
        // 最后一个item设置为footerView
        if(mType == 0){
            if (position + 1 == getItemCount()) {
                return 1;
            } else {
                return 0;
            }
        }
        return 0;
    }

    /**
     * //上拉加载更多
     * PULLUP_LOAD_MORE=0;
     * //正在加载中
     * LOADING_MORE=1;
     * //加载完成已经没有更多数据了
     * NO_MORE_DATA=2;
     * @param status
     */
    public void changeMoreStatus(int status){
        load_more_status=status;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        if(mType == 0){
            if(mListCannotGet.size() < 6 ){
                return mListCannotGet.size();
            }else {
                return mListCannotGet.size()+1;
            }
        }else if(mType == 2){
            return  mListCanGet.size();
        }
      return 0;
    }

    @Override
    public void onClick(View v) {
          if(mType == 2){
              tv3OnClick((int)v.getTag());
          }
    }

    private static class VoucherHolder extends RecyclerView.ViewHolder{
        TextView mTVName;            //名称
        TextView mTVTime;           //时间
        TextView mTVHairtime;      //发送时间
        TextView mTVcollartime;   //领取时间
        TextView mTVCollar ;      //领取
        ImageView mIVcollar;     //展示领取的图片
        LinearLayout lLCollar;  //领取
        LinearLayout lLCollartime;  //领取的时间

        private VoucherHolder(Context context,View view,int type) {
            super(view);
            mTVName = (TextView)view.findViewById(R.id.adapter_voucher_name);
            mTVTime = (TextView)view.findViewById(R.id.adapter_voucher_time);
            mTVCollar = (TextView)view.findViewById(R.id.adapter_voucher_tv_collar);
            mTVHairtime = (TextView)view.findViewById(R.id.adapter_voucher_hairtime);
            mTVcollartime = (TextView)view.findViewById(R.id.adapter_voucher_collartime);
            mIVcollar = (ImageView) view.findViewById(R.id.adapter_voucher_iv_collar);
            lLCollar = (LinearLayout)view.findViewById(R.id.adapter_voucher_ll_collar);
            lLCollartime = (LinearLayout)view.findViewById(R.id.adapter_voucher_ll_collartime);
            if(type == 2){
                mIVcollar.setVisibility(View.GONE);
                lLCollar.setVisibility(View.VISIBLE);
                lLCollartime.setVisibility(View.GONE);
            }
        }
    }


    /**
     * 底部FootView布局
     */
    private static class FootViewHolder extends  RecyclerView.ViewHolder{
        private TextView tv_Name;
        private ProgressBar mProgressBar;
        private FootViewHolder(View view) {
            super(view);
            tv_Name=(TextView)view.findViewById(R.id.adapter_periphery_button_tv);
            mProgressBar = (ProgressBar)view.findViewById(R.id.adapter_periphery_button_pb);
        }
    }

    /**
     * 领取券
     */
    private void tv3OnClick(final int p){
        HashMap map = new HashMap<>();
        String id = (String) SharedPreferencesUtils.getParam(mContext, HomeUtil.mUseridDB,"");
        String token = (String) SharedPreferencesUtils.getParam(mContext, HomeUtil.mTokenDB,"");
        map.put("userid",id);
        map.put("ticketid",mListCanGet.get(p).getTicketid());
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(map); //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.getUrlNew().RECEIVE_COUPON,stringJson,token,id,time);
        Map map1 = StringUtil.getStringUtilNew().getMapNew(mContext,stringJson,token,id,Url.getUrlNew().RECEIVE_COUPON,stirngSign,time);
        LogUtil.eE("","..tv3OnClick..onSuccess..."+stringJson);
        GreenTreeNetworkUtil.getInstance().doPost(mContext,MyApplication.getApp().getFWQString(),1,map1,new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    LogUtil.eE("","..tv3OnClick..onSuccess..."+response);
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.getInt("code");
                    if(code == 1){
                        delete(p);
                        Toast.makeText(mContext,"领取成功",Toast.LENGTH_SHORT).show();
                    }else if(code == -1){
                        Toast.makeText(mContext,mContext.getString(R.string.FWQ),Toast.LENGTH_SHORT).show();
                    }else if(code == -2){
                        CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(mContext);
                        crowdRetunDialog.show();
                    }else {
                        Toast.makeText(mContext,"领取失败",Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(mContext,"领取失败",Toast.LENGTH_SHORT).show();
                }

            }

            @Override public void onFailure(Throwable error) {
                Toast.makeText(mContext,"领取失败",Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void delete(int p){
        mListCanGet.remove(p);
        notifyItemRemoved(p);
        notifyItemRangeChanged(0,mListCanGet.size()-p);
        EventBus.getDefault().post("balance");
    }
}
